package cn.iocoder.yudao.module.system.service.school;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.school.vo.SchoolPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.school.vo.SchoolRespVO;
import cn.iocoder.yudao.module.system.controller.admin.school.vo.SchoolSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.employmentdir.EmploymentDirDO;
import cn.iocoder.yudao.module.system.dal.dataobject.school.SchoolDO;
import cn.iocoder.yudao.module.system.dal.mysql.school.SchoolMapper;
import cn.iocoder.yudao.module.system.service.employmentdir.EmploymentDirService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.val;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 院校 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class SchoolServiceImpl implements SchoolService {

    @Resource
    private SchoolMapper schoolMapper;

    @Resource
    private EmploymentDirService employmentDirService;

    @Override
    public Long createSchool(SchoolSaveReqVO createReqVO) {
        // 插入
        SchoolDO school = BeanUtils.toBean(createReqVO, SchoolDO.class);
        schoolMapper.insert(school);
        // 返回
        return school.getId();
    }

    @Override
    public void updateSchool(SchoolSaveReqVO updateReqVO) {
        // 校验存在
        validateSchoolExists(updateReqVO.getId());
        // 更新
        SchoolDO updateObj = BeanUtils.toBean(updateReqVO, SchoolDO.class);
        schoolMapper.updateById(updateObj);
    }

    @Override
    public void deleteSchool(Long id) {
        // 校验存在
        validateSchoolExists(id);
        // 删除
        schoolMapper.deleteById(id);
    }

    private void validateSchoolExists(Long id) {
        if (schoolMapper.selectById(id) == null) {
            throw exception(new ErrorCode(404,"院校不存在"));
        }
    }

    @Override
    public SchoolDO getSchool(Long id) {
        return schoolMapper.selectById(id);
    }

    @Override
    public PageResult<SchoolDO> getSchoolPage(SchoolPageReqVO pageReqVO) {
        // 获取原始查询结果
        PageResult<SchoolDO> schoolDOPageResult = schoolMapper.selectPage(pageReqVO);

        // 如果传递了dirId，需要进行过滤
        if (pageReqVO.getDirId() != null) {
            // 获取就业方向信息
            EmploymentDirDO employmentDir = employmentDirService.getEmploymentDir(pageReqVO.getDirId().longValue());

            if (employmentDir != null && StringUtils.isNotBlank(employmentDir.getSchoolIds())) {
                // 解析对口院校ID列表
                Set<Long> matchingSchoolIds = Arrays.stream(employmentDir.getSchoolIds().split(","))
                        .map(String::trim)
                        .filter(StringUtils::isNotBlank)
                        .map(Long::parseLong)
                        .collect(Collectors.toSet());

                // 过滤结果，只保留与就业方向对口院校匹配的学校
                List<SchoolDO> filteredList = schoolDOPageResult.getList().stream()
                        .filter(school -> matchingSchoolIds.contains(school.getId()))
                        .collect(Collectors.toList());

                // 更新分页结果
                schoolDOPageResult.setList(filteredList);
                schoolDOPageResult.setTotal((long) filteredList.size());
            } else {
                // 如果就业方向不存在或没有对口院校，返回空列表
                schoolDOPageResult.setList(Collections.emptyList());
                schoolDOPageResult.setTotal(0L);
            }
        }

        return schoolDOPageResult;
    }

    @Override
    public List<Map<String, Object>> getAllSchool(String name) {
        QueryWrapperX<SchoolDO> queryWrapper = new QueryWrapperX<>();
        if (name != null) {
            queryWrapper.like("name", name);
        }

        List<SchoolDO> schoolDOS = schoolMapper.selectList(queryWrapper);

        // 转换为前端可用的级联选择器格式
        Map<String, List<SchoolDO>> provinceMap = new HashMap<>();

        // 按省份分组
        for (SchoolDO school : schoolDOS) {
            String province = school.getProvince();
            if (!provinceMap.containsKey(province)) {
                provinceMap.put(province, new ArrayList<>());
            }
            provinceMap.get(province).add(school);
        }

        // 构建前端需要的层级结构
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, List<SchoolDO>> entry : provinceMap.entrySet()) {
            Map<String, Object> provinceNode = new HashMap<>();
            String province = entry.getKey();
            List<SchoolDO> schools = entry.getValue();

            // 确保至少有一所学校，以获取省份名称
            if (!schools.isEmpty()) {
                provinceNode.put("value", province);
                provinceNode.put("label", schools.get(0).getProvinceName());

                // 构建子节点（学校列表）
                List<Map<String, Object>> children = new ArrayList<>();
                for (SchoolDO school : schools) {
                    Map<String, Object> schoolNode = new HashMap<>();
                    schoolNode.put("value", school.getId());
                    schoolNode.put("label", school.getName());
                    children.add(schoolNode);
                }
                provinceNode.put("children", children);
                result.add(provinceNode);
            }
        }
        return result;
    }

    @Override
    public List<SchoolDO> getAllSchools(String name) {
        QueryWrapperX<SchoolDO> queryWrapper = new QueryWrapperX<>();
        if (name != null) {
            queryWrapper.like("name", name);
        }

        List<SchoolDO> schoolDOS = schoolMapper.selectList(queryWrapper);
        return schoolDOS;
    }
}